<?php
define('ERR_LOGFILE', 'ERROR: Cannot open logfile. (maybe \'chmod 777 tmp\' ?)');
define('ERR_DB', 'ERROR: Cannot open database connection. (check your configs)');
define('ERR_DBQUERY', 'ERROR: Cannot query database');
define('ERR_GOOGLE', 'ERROR: Awh shucks, I searched and searched but found nothing. If you know you should have found somthing you may be blacklisted (lasts about 3-4 hrs).');
require_once 'config.php';
$dbh = mysql_connect($mysqldb['host'], $mysqldb['user'], $mysqldb['pass']);
if(!$dbh) die(ERR_DB);
mysql_select_db($mysqldb['db'], $dbh);
$sql='select * from status;';
$rsSearchResults = mysql_query($sql, $dbh) or die("Line: " . __LINE__ ." ". mysql_error());
$succ = 0;
$catyou = 0;
while ($l = mysql_fetch_array($rsSearchResults)) {
	$total = $l["1"];
	$succ = $l["2"];
	$term = $l["3"];
	$query_id = $l["4"];
}

if(!isset($_POST['signup'])){ // show the information for modifying
?>

<script type="text/javascript">
	function ajaxFunction()
	{
		var id = document.getElementById('query_option').value;
		if(parseInt(id)<0){
		 document.getElementById('query_info').innerHTML = '';
		 return false;
		 }
		var xmlHttp;
		var http_query = '';
		try
		  {
		  // Firefox, Opera 8.0+, Safari
		  xmlHttp=new XMLHttpRequest();
		  }
		catch (e)
		  {
		  // Internet Explorer
		  try
		    {
		    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		    }
		  catch (e)
		    {
		    try
		      {
		      xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		      }
		    catch (e)
		      {
		      alert("Your browser does not support AJAX!");
		      return false;
		      }
		    }
		  }
		xmlHttp.onreadystatechange=function()
	    {
	    	if(xmlHttp.readyState == 4){
				document.getElementById('query_info').innerHTML = xmlHttp.responseText;
	    	}
	    }
	  //send the request
	  	http_query = 'select_query.php?query_num=' + id;
	  	xmlHttp.open("GET", http_query, true);
	   	xmlHttp.send(null);
	}
</script>
<?php
	$message = '<form action="register.php" method="post">';
	$message .= '<div align="left" style="width: 60%; margin-left: 30%;" id="query_config" name="query_config">';
	$message .= '<div style="width: 100%" id="title" align="center"><h2>Account registration page</h2></div>';
	$message .= "<b><label style=\"width: 20%; float: left\">Search term:</label><label style=\"width: 60%; margin-left: 5%\">$term</label></b><br>";
	$message .= "<b><label style=\"width: 25%; float: left\">Registered pages:</label><label style=\"width: 60%; margin-left: 0%\">$succ</label></b><br>";
	$message .= "<b><label style=\"width: 15%; float: left\">Total pages:</label><label style=\"width: 60%; margin-left: 10%\">$total</label></b><br>";
	$message .= '<br><b><label style="width: 15%; float: left">Query to run:</b></label>';
	if($query_id == -1){ // first time running the query{
		$message .= '<select id="query_option" name="query_option" onchange="ajaxFunction(this.value);" style="margin-left: 8%" value="2">';
		$message .= "<option value=\"-1\">Select a query</option>";
		for($i=0; $i<count($queries); $i++) {
			$message .= "<option value=\"$i\">" . $i . "</option>";
		}
		$message .= "</select>";
	}else{
		$message .= "<b><label style=\"width: 60%; margin-left: 10%\">$query_id</label></b><br>";
		$message .= '<br><div align="left" style="width: 100%;" id="query_info" name="query_config">';
		$query = $queries[$query_id];
		foreach($query as $name => $value) {
			if($name=="post" || $name=="term") continue;
			$message .= "<b><label style=\"width: 15%; float: left\">$name:</label></b>";
			if($name=='term')
				$message .= "<textarea row=\"3\" col=\"50\" id=\"$name\" name=\"$name\" style=\"margin-left: 15%; width: 60%\">". str_replace("\"", "", $value) . "</textarea><br>";
			else
				$message .= "<input type=\"text\" id=\"$name\" name=\"$name\" value=\"" . str_replace("\"", "", $value) . "\" style=\"margin-left: 10%; width: 60%\" /><br>";
		}
			$message .= "<b><label style=\"width: 10%; float: left\">email:</label></b><input type=\"text\" id=\"email\" name=\"email\" value=\"" . str_replace("\"", "", $email) . "\" style=\"margin-left: 15%; width: 60%\" /><br>";
			$message .= "<b><label style=\"width: 10%; float: left\">user:</label></b><input type=\"text\" id=\"user\" name=\"user\" value=\"" . str_replace("\"", "", $user) . "\" style=\"margin-left: 15%; width: 60%\" /><br>";
			$message .= "<b><label style=\"width: 10%; float: left\">pass:</label></b><input type=\"text\" id=\"pass\" name=\"pass\" value=\"". str_replace("\"", "", $pass) . "\" style=\"margin-left: 15%; width: 60%\" /><br>";
		if(strstr($query['post'], 'first_name') != false ){
			$message .= "<b><label style=\"width: 10%; float: left\">firstname:</label></b><input type=\"text\" id=\"firstname\" name=\"firstname\" value=\"". $firstname . "\" style=\"margin-left: 15%; width: 60%\" /><br>";
		}
		if(strstr($query['post'], 'last_name') != false ){
			$message .= "<b><label style=\"width: 10%; float: left\">lastname:</label></b><input type=\"text\" id=\"lastname\" name=\"lastname\" value=\"". $lastname . "\" style=\"margin-left: 15%; width: 60%\" /><br>";
		}
		$message .= '</div>';
	}
	$message .= '<div align="left" style="width: 100%;" id="query_info" name="query_config"></div>';
	$message .= '<br><div><input type="submit" value="submit" style="width: 10%; margin-left: 30%;" /><br>';
	$message .= "<br><a href=\"javascript:history.go(-1);\" style=\"width: 10%; margin-left: 30%;\">Back</a></div>";
	$message .= '</div></form>';
	echo $message;

}else{	// collect information after modifying
	if(isset($_POST['query_option'])){
		if ($_POST['query_option'] == -1){
			echo "<div><b>It's the first time you run the script, so you should choose 'start' instead of 'continue'</b>";
			echo "<br><a href=\"javascript:history.go(-1);\">Back</a></div>";
			exit;
		}else{
			//update the query_id
			$sql = 'UPDATE status SET query_id ='. $_POST['query_option'] . ' WHERE id = 1';
			mysql_query($sql, $dbh) or die("Line: " . __LINE__ ." ". mysql_error());
			$query_id = $_POST['query_option'];
		}
	}
	$query = $queries[$query_id];
	// account information
	if(isset($_POST['email']))$email = $_POST['email'];
	if(isset($_POST['user']))$user = $_POST['user'];
	if(isset($_POST['pass']))$pass = $_POST['pass'];
	if(isset($_POST['firstname']))$firstname = $_POST['firstname'];
	else
		$firstname = '';
	if(isset($_POST['lastname']))$firstname = $_POST['firstname'];
	else
		$lastname = '';
	if(isset($_POST['signup'])) $query['signup'] = $_POST['signup'];
	if(isset($_POST['succ'])) $query['succ'] = $_POST['succ'];
	// populate post
	$patterns = array();
	$replacements = array();
	$patterns[0] = '/email=([^&]+)&/';
	$patterns[1] = '/user=([^&]+)&/';
	$patterns[2] = '/passA=([^&]+)&/';
	$patterns[3] = '/passB=([^&]+)&/';
	$patterns[4] = '/first_name=([^&]*)&/';
	$patterns[5] = '/last_name=([^&]*)&/';

	$replacements = array("email=" . $email . "&", "user=" . $user . "&", "passA=" . $pass . "&", "passB=" . $pass . "&", "first_name=" . $firstname . "&", "last_name=" . $lastname . "&");
	$query['post'] = preg_replace($patterns, $replacements, $query['post']);
	if($query['post'] == NULL){
		echo 'There is an error occurred when applying new post for the query';
	}
	$query['term'] = $term;
	// this pattern for the query 2 only
	$patterns[0] = '/txtEmailAddress=([^&]+)&/';
	$patterns[1] = '/txtPassword1=([^&]+)&/';
	$patterns[2] = '/txtFirstName=([^&]+)&/';
	$patterns[3] = '/txtLastName=([^&]+)&/';
	$patterns[4] = '/txtPassword2=([^&]*)&/';
	$replacements = array("txtEmailAddress=" . $email . "&",
							"txtPassword1=" . $pass . "&",
							"txtFirstName=" . $pass . "&",
							"txtLastName=" . $pass . "&",
							"txtPassword2=" . $pass . "&"

				);
	$query['post'] = preg_replace($patterns, $replacements, $query['post']);
	if($query['post'] == NULL){
		echo 'There is an error occurred when applying new post for the query';
	}
	$catyou = 0;
	// finish populate the query, start registering.
	$sql = "SELECT id, url, googlerank, registered FROM signmeup WHERE registered = 0 and processed = 0";
	$res = mysql_query($sql, $dbh) or die("Line: " . __LINE__ ." ". mysql_error());
	while ($rec = mysql_fetch_array($res)) {
		$id = $rec["0"];
		$url = $rec["1"];
		$rank = $rec["2"];
		$reged = $rec["3"];
		$ch = curl_init($url . $query['signup']);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $query['post']);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		$regpage = curl_exec($ch);
		curl_close($ch);
		// update the processed status of the page
		$sql = sprintf("UPDATE signmeup SET processed = 1 WHERE id=%d", $id);
		mysql_query($sql, $dbh) || die("Line: " . __LINE__ ." ". ERR_DBQUERY . " " . mysql_error($dbh));

		// we get domain name
		$urlh=parse_url($url);
		$urlh=$urlh['host'];
		// parse the result page
		if(preg_match('/'.$query['succ'].'/i', $regpage)) {
			$sql = sprintf("UPDATE signmeup SET registered = 1, user='%s', pass='%s', url='%s' WHERE id=%d", $user, $pass, $url . $query['signup'], $id);
			mysql_query($sql, $dbh) || die("Line: " . __LINE__ ." ". ERR_DBQUERY . " " . mysql_error($dbh));
			$succ++;
			//update status
			$sql = sprintf("UPDATE status SET success=%d WHERE id=1;", $succ);
			mysql_query($sql, $dbh) || die("Line: " . __LINE__ ." ". ERR_DBQUERY . ": " . mysql_error($dbh) );
		} else if(preg_match('/Invalid Code Entered/i', $regpage)) {
			// no duplicate domains
			if(!mysql_num_rows(mysql_query("SELECT url FROM `capcha` WHERE LOCATE('//{$urlh}/',url) LIMIT 1"))){
				$sql = sprintf("INSERT INTO capcha(url,user,pass,post,host,googlerank, success_string, signmeup_id) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', %d);", $url . $query['signup'], $user, $pass, $query['post'], $url, $rank, $query['succ'], $id);
				$catyou++;
				if(!mysql_query($sql, $dbh)){
					echo "Line: " . __LINE__ ." ". ERR_DBQUERY.mysql_error();
					continue;
				}
			}
		} else { //DEBUGecho "FAIL: ".$target['Url'].'<br>';
		}
	}
	echo "DONE!<br>Total: $total<br>Success: $succ<br>CAPTCHA: $catyou";
	echo "<br><a href=\"javascript:history.go(-1);\">Back</a></div>";
}
mysql_close($dbh);

?>
